import { userLocalKey } from 'common/js/config'
import { getLocalStorage, removeLocalStorage } from 'common/js/dom'

// 过滤模糊查询
export const filterLikeSearch = str => `%${str}%`

// 获取当前用户本地存储信息
export const getUserIng = () => getLocalStorage(userLocalKey)

// 设置当前用户本地存储信息
export const setUserIng = obj => getLocalStorage(userLocalKey, obj)

// 删除当前用户本地存储信息
export const removeUserIng = () => removeLocalStorage(userLocalKey)

// 深拷贝一个Object
export const cloneObj = obj => JSON.parse(JSON.stringify(obj))
// export const cloneObj = obj => {
//   if (typeof obj !== 'object') {
//     return obj
//   }
//   var s = {}
//   if (obj.constructor === Array) {
//     s = []
//   }
//   for (var i in obj) {
//     s[i] = cloneObj(obj[i])
//   }
//   return s
// }

// 过滤时间格式
export const timeFilter = (time, format) => {
  var o = {
    'M+': time.getMonth() + 1, // month
    'd+': time.getDate(), // day
    'H+': time.getHours(), // hour
    'm+': time.getMinutes(), // minute
    's+': time.getSeconds(), // second
    'q+': Math.floor((time.getMonth() + 3) / 3), // quarter
    'S': time.getMilliseconds() // millisecond
  }

  if (/(y+)/.test(format)) {
    format = format.replace(RegExp.$1, (time.getFullYear() + '').substr(4 - RegExp.$1.length))
  }

  for (var k in o) {
    if (new RegExp('(' + k + ')').test(format)) {
      format = format.replace(RegExp.$1, RegExp.$1.length === 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length))
    }
  }
  return format
}

// 过滤ajax数据，使其用表单形式传输
export const changeDataType = json => {
  var a = Object.keys(json).map(
    function (k) {
      return encodeURIComponent(k) + '=' + encodeURIComponent(json[k])
    }
  ).join('&')

  return a
}

// 返回登录页面
export const backLogin = ({ alertMessage } = {}) => {
  removeUserIng()
  if (alertMessage !== undefined) {
    alert(alertMessage)
  }
  window.location.href = '/'
}
